<template>
  <div class="document-list-container">
    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="文档标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入文档标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="文档类型">
          <el-select
            v-model="searchForm.docType"
            placeholder="请选择文档类型"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="option in DOC_TYPE_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keywords"
            placeholder="请输入关键词"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="发布日期">
          <el-date-picker
            v-model="publishDateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增文档
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="文档标题" min-width="200" show-overflow-tooltip />
        
        <el-table-column label="文档类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getDocTypeTagType(row.docType)">
              {{ DOC_TYPES[row.docType] }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="source" label="来源" width="150" show-overflow-tooltip />
        <el-table-column prop="keywords" label="关键词" width="150" show-overflow-tooltip />
        <el-table-column prop="publishDate" label="发布日期" width="160" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="info" size="small" @click="handleDetail(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 文档表单弹窗 -->
    <document-form
      v-model:visible="formVisible"
      :document-data="currentDocument"
      @success="handleFormSuccess"
    />

    <!-- 文档详情弹窗 -->
    <document-detail
      v-model:visible="detailVisible"
      :document-id="currentDocumentId"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, View, Edit, Delete } from '@element-plus/icons-vue'
import { getDocumentPage, deleteDocument, DOC_TYPES, DOC_TYPE_OPTIONS } from '../../api/document'
import DocumentForm from './components/DocumentForm.vue'
import DocumentDetail from './components/DocumentDetail.vue'

// 搜索表单
const searchForm = reactive({
  title: '',
  docType: null,
  keywords: '',
  publishStartDate: '',
  publishEndDate: ''
})

// 日期范围
const publishDateRange = ref([])

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 表单弹窗
const formVisible = ref(false)
const currentDocument = ref(null)

// 详情弹窗
const detailVisible = ref(false)
const currentDocumentId = ref(null)

// 获取文档类型标签样式
const getDocTypeTagType = (docType) => {
  const typeMap = {
    0: 'danger',   // 法律 - 红色
    1: 'primary',  // 案例 - 蓝色
    2: 'warning',  // 判决书 - 橙色
    3: 'success'   // 文章 - 绿色
  }
  return typeMap[docType] || 'info'
}

// 处理日期范围变化
const handleDateRangeChange = (dateRange) => {
  if (dateRange && dateRange.length === 2) {
    searchForm.publishStartDate = dateRange[0]
    searchForm.publishEndDate = dateRange[1]
  } else {
    searchForm.publishStartDate = ''
    searchForm.publishEndDate = ''
  }
}

// 获取文档列表
const fetchDocumentList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await getDocumentPage(params)
    if (response.code === 200) {
      tableData.value = response.data.records
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取文档列表失败:', error)
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  fetchDocumentList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    docType: null,
    keywords: '',
    publishStartDate: '',
    publishEndDate: ''
  })
  publishDateRange.value = []
  pagination.pageNum = 1
  fetchDocumentList()
}

// 新增文档
const handleAdd = () => {
  currentDocument.value = null
  formVisible.value = true
}

// 查看详情
const handleDetail = (row) => {
  currentDocumentId.value = row.id
  detailVisible.value = true
}

// 编辑文档
const handleEdit = (row) => {
  currentDocument.value = { ...row }
  formVisible.value = true
}

// 删除文档
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除文档 "${row.title}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteDocument(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchDocumentList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文档失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  fetchDocumentList()
}

// 页码改变
const handleCurrentChange = (page) => {
  pagination.pageNum = page
  fetchDocumentList()
}

// 表单提交成功
const handleFormSuccess = () => {
  fetchDocumentList()
}

// 页面加载时获取数据
onMounted(() => {
  fetchDocumentList()
})
</script>

<style scoped>
.document-list-container {
  padding: 20px;
}

.search-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .document-list-container {
    padding: 15px;
  }
  
  .search-card {
    padding: 15px;
  }
  
  .table-card {
    padding: 15px;
  }
  
  :deep(.el-form--inline .el-form-item) {
    display: block;
    margin-bottom: 15px;
  }
  
  :deep(.el-form--inline .el-form-item__content) {
    margin-left: 0 !important;
  }
}
</style>
